package oj;

import java.util.Stack;

public class LC224 {

    public int calculate(String s) {
        Stack<Integer> stack=new Stack<>();
        int num=0;
        char sign='+';
        char[] ch=s.toCharArray();
        for(int i=0;i<s.length();i++){
            char c=ch[i];
            if(Character.isDigit(c)){
                num=num*10+(c-'0');
            }

            if(c=='('){
                int j=i+1;
                int counterPartition =1;//计算括号的数量，保证找到对应的一组括号
                while(counterPartition >0){
                    if(ch[j]=='('){
                        counterPartition ++;
                    }
                    if(ch[j]==')'){
                        counterPartition --;
                    }
                    j++;
                }
                num=calculate(s.substring(i+1,j-1));
                i=j-1;
            }

            if(!Character.isDigit(c) && c!=' ' || i==s.length()-1){
                if(sign=='+'){
                    stack.push(num);
                }else if(sign=='-'){
                    stack.push(-1*num);
                }else if(sign=='*'){
                    stack.push(stack.pop()*num);
                }
                sign=c;
                num=0;
            }
        }
        int ans=0;
        while(!stack.isEmpty()){
            ans+=stack.pop();
        }
        return ans;
    }

}
